<?php
namespace app\wechat\controller;
use app\common\model\Address;
use app\common\model\Message;
use app\common\model\Product_info;
use app\common\model\User_goods;
use app\common\model\Wechat as WechatModel;
use app\common\model\User;
use app\common\model\China;
use app\common\model\Dev_info;
use app\common\model\Engin;
use app\common\model\Order;
use app\common\model\Relation;
use think\Controller;
use think\Db;
use think\Session;
Vendor('Wechat.Wechat');

class Cons extends Controller{

	public function __construct(){

    	parent::__construct();

	}

	/**
	 * 微信网页访问存session
	 * @return [type] [description]
	 */
	public function saveWechat(){
		// $relation = new Relation();

  //       $userModel = new User();
  //       $uid = 20;

  //       //查询用户是否存在
  //       $field = 'uid,name,valid,photo';
  //       $user = $userModel->getOne($field,['uid'=>$uid]);
  //               //获取微信用户信息
  //       $uinfo["id"] = $user["uid"];
  //       $uinfo["name"] = $user["name"];
  //       $uinfo["type"] = $relation->getAlltype($user['uid'],false,1,true);
  //       $uinfo["valid"] = $user["valid"];
  //       $uinfo["duty"] = $relation->identity($user['uid'],true,1);
  //       session('user',$uinfo);

		// return true;


    	$options["appid"] = config("WECHAT_APPID");
        $options["appsecret"] = config("WECHAT_APPSERVER");
        $weObj = new \Wechat($options);
        $return =$weObj->getOauthAccessToken();
        if($return){
			$relation = new Relation();
            $userModel = new User();
            //查询用户是否存在
            $field = 'uid,name,valid,photo';
            $user = $userModel->getOne($field,['third_id'=>$return["openid"]]);
            if($user){
            	if(!Session::has('user')){
            		//获取微信用户信息
        			$info = $weObj->getOauthUserinfo($return["access_token"],$return["openid"]);
	                $uinfo["openid"] = $return["openid"];
	                $uinfo["id"] = $user["uid"];
                    $uinfo["name"] = $user["name"];
	                $uinfo["type"] = $relation->getAlltype($user['uid'],false,1,true);
	                $uinfo["valid"] = $user["valid"];
	                $uinfo["duty"] = $relation->identity($user['uid'],true,1);
	                session('user',$uinfo);
            	}
            }else{
	    
	        	//获取微信用户信息
                $info = $weObj->getUserInfo($return['openid']); 
            	//不存在 则添加
            	$add["third_id"] = $return["openid"];
                $add["t1"] = time();
                $add["ms"] = isset($return["unionid"])?$return["unionid"]:'';
                $add["valid"] = 0;
                $uid = $userModel->inGetData($add);
                
                $uinfo['id'] = $uid;
                $uinfo["openid"] = $return["openid"];
                $uinfo["valid"] = 0;
                $uinfo['type'] = array();
                $uinfo["name"] = $info['nickname'];
                $uinfo["duty"] = '';
 
                session('user',$uinfo);

            }
        }

        if(config('CHANCE')){
        	//一定概率事件中 删除2小时之外 未认证的用户
        	$userModel = new User();
        	$where['valid'] = 0;
        	$where['t1'] = ['<',time()-7200];
        	// $userModel->where($where)->delete();
        }
	}

	/**
	 * 用户认证
	 * @return [type] [description]
	 */
	public function reg(){
		$this->saveWechat();

		if (request()->isPost()){
            
            $data=input('post.');
            $uid = session('user.id');

            $userModel = new User();
            $res = $userModel->userCheck($data);

            if ($res['state']){

            	$result = $userModel->allowField(true)->save($res['msg'],['uid'=>$uid]);
            	if($result){
            		$type = explode(",",$data['type']);
            		$place = config('PLACE');
            		$relation = new Relation();
	            	foreach ($type as $value) {

	            		$rarr['uid'] = $uid;
	            		$rarr['rid'] = $value;
	            		$rarr['ctime'] = time();
	            		if($value==$place['PLACE_RMAN_OPEN']['id'] || $value==$place['PLACE_RMAN_AYS']['id']){
	            			//资源人
	            			$tuser = $userModel->getOne('uid',['phone'=>$data['tel']]);

	            			$rarr['referral'] = $tuser['uid'];
	            			$rarr['tel'] = $data['tel'];
	            		}

	        			$relation->insert($rarr);
	            		unset($rarr);
	            	}

	            	$this->success('提交成功',url('Cons/infos'));
            	}else{
               		$this->error('提交失败,请重试!');
            	}
            }else{
                $this->error($res['msg']);
            }
        }

        return view();
	}

	/**
	 * 添加身份
	 * @return [type] [description]
	 */
	public function autype(){
		$this->saveWechat();
        $uid = session('user.id');
        $userModel = new User();

        $data = $userModel->getOne('*',['uid'=>$uid]);
        $data['note'] = json_decode($data['note'],true);
		if(request()->isPost()){
            
            $post=input('post.');
            $res = $userModel->userUpd($post,$data);
            if ($res['state']){

            	$result = $userModel->allowField(true)->save($res['msg'],['uid'=>$uid]);

        		$type = explode(",",$post['type']);
        		$place = config('PLACE');
        		$relation = new Relation();
        		//先删除未审核通过的
        		$relation->where(['uid'=>$uid,'auth'=>2])->delete();
            	foreach ($type as $value) {

            		$rarr['uid'] = $uid;
            		$rarr['rid'] = $value;
            		$rarr['ctime'] = time();
            		if($value==$place['PLACE_RMAN_OPEN']['id'] || $value==$place['PLACE_RMAN_AYS']['id']){
            			//资源人
            			$tuser = $userModel->getOne('uid',['phone'=>$post['tel']]);

            			$rarr['referral'] = $tuser['uid'];
            			$rarr['tel'] = $post['tel'];
            		}

        			$relation->insert($rarr);
            		unset($rarr);
            	}

            	$this->success('提交成功',url('Cons/infos'));

            }else{
                $this->error($res['msg']);
            }
        }

        $relationModel = new Relation();
        $data['utype'] = $relationModel->identity($uid,false,1,true);        
		return view('',['title'=>'添加身份','data'=>json_encode($data)]);
	}

	/**
	 * 用户中心
	 * @return [type] [description]
	 */
	public function infos(){

		$this->saveWechat();

		$userModel = new User();
		$relationModel = new Relation();
		$chinaModel = new China();

		$uid = session('user.id');

		$info = $userModel->getOne('*',['uid'=>$uid]);
		//已认证,认证成功
		$info['addres'] = '';
		if($info['pid']){
			$pid = $chinaModel->areas($info['pid']);
			$info['addres'] .= $pid['name'];
			if($info['cid']){
				$cid = $chinaModel->areas($info['cid']);
				$info['addres'] .= $cid['name'];
				if($info['aid']){
					$aid = $chinaModel->areas($info['aid']);
					$info['addres'] .= $aid['name'];
				}
			}
		}

		$utype = $relationModel->identity($uid,false,null,true);
         
		$info['utype'] = ['dex'=>'','cex'=>'','pex'=>'','uty'=>''];
		foreach ($utype as $key=>$value) {
			if($value['auth']==0){
				$info['utype']['dex'] .= $value['identity']." ";
			}elseif($value['auth']==1){
				$info['utype']['cex'] .= $value['identity']." ";
			}elseif($value['auth']==2){
				$info['utype']['pex'] .= $value['identity']." ";
			}

			$info['utype']['uty'][$key] = $value['rid'];
		}

        $message = new Message();
        $num = $message->getUnreadMsgNum($uid);
        $place = config('PLACE');

		return view('cons/infos',['data'=>$info,'num'=>$num,'place'=>$place]);
		
	}

	/**
	 * 业务审核
	 * @return [type] [description]
	 */
	public function businex(){
		return view();
	}

	/**
	 * 订单业务
	 * @return [type] [description]
	 */
	public function businlist(){
		return view();
	}

	/**
	 * 产品订单详情
	 * @return [type] [description]
	 */
	public function busininfos(){
		return view();
	}
	
	/**
	 * 项目订单详情
	 * @return [type] [description]
	 */
	public function businlistdetail(){
		return view();
	}

    /**
     * 产品订单审核详情
     * @return [type] [description]
     */
	public function oreview(){
	    return view();
    }

	/**
     * 项目订单审核详情
     * @return [type] [description]
     */
	public function ereview(){
	    return view();
    }


	/**
	 * 用户信息修改
	 * @return [type] [description]
	 */
	public function uinfo(){
		$userModel = new User();

		$uid = session('user.id');
        $where['uid']= $uid;

        if(request()->isPost()) {
            $data=input('post.');
            $res = $userModel->updateFieldsById($where, $data);
            if ($res!==false) {
                show(1, '操作成功');
            } else {
                show(0, '操作失败');
            }
        }else{

            $field = "*";
            $info = $userModel->getOne($field,$where);
            $chinaModel = new China();
            
            $info['addres'] = '';
	        if($info['pid']){
	            $pid = $chinaModel->areas($info['pid']);
	            $info['addres'] .= $pid['name'];
	            if($info['cid']){
	                $cid = $chinaModel->areas($info['cid']);
	                $info['addres'] .= $cid['name'];
	                if($info['aid']){
	                    $aid = $chinaModel->areas($info['aid']);
	                    $info['addres'] .= $aid['name'];
	                }
	            }
	        }

	        $info['note'] = json_decode($info['note'],true);

            return view('',['data'=>$info]);
        }
	}

	/**
	 * 绑定手机
	 * @return [type] [description]
	 */
	public function btel(){
		return view();
	}

	/**
	 * 设备列表
	 * @return [type] [description]
	 */
	public function devs(){

		$this->saveWechat();

		$uid = session('user.id');
		// $devModel = new Dev_info();
		// $data = $devModel->getDevAll(['owner'=>$uid]);
		$data = array();
		return view('',['data'=>$data]);
	}

	/**
	 * 设备详情
	 * @return [type] [description]
	 */
	public function devinfo(){
		return view('');
	}

	/**
	 * 手动添加设备
	 * @return [type] [description]
	 */
	public function adds(){
		$this->saveWechat();
		$uname = session('user.name');
		$uid = session('user.id');

		if(request()->isPost()){
		}

		return view('',['uname'=>$uname]);
	}

	/**
	 * 提交项目订单
	 * @return [type] [description]
	 */
	public function addpro(){
		$this->saveWechat();
		$uid = session('user.id');
		$uname = session('user.name');
		if(request()->isPost()){
			$post = input('post.');
			if(!$uid){
				show(0,'用户登录超时,请重新进入此页面');
			}
			if(!$post['cname'] || !$post['amoneys'] || !$post['content'] || !$post['cycles']){
				show(0,'信息填写不完整');
			}
            $fileName = time().rand(1,999);
            $res = uploadFile('contract',$fileName,'/uploads/engin/',5);
            
			if ($res['state'] == 0) show(0,$res['msg']);
            $filePath = $res['msg'];
            $time = time();
            $eid  = date('YmdHis',time()).rand(1000,9999);
            $user_id = input('post.uid') ? input('post.uid') : $uid; //负责人的uid

            $enginModel = new Engin();
            $data = [
                'eid'=>$eid,
                'uid'=>$uid,
                'cname'=>$post['cname'],
                'contract'=>$filePath,
                'amoneys'=>$post['amoneys'],
                'content'=>$post['content'],
                'cycles'=>$post['cycles'],
                'remarks'=>$post['remarks'],
                'ct'=>$time
            ];

            $insertId = $enginModel->insert($data,false,true);
            if($insertId){
                $affairModel = new \app\manage\controller\Affairengineering();
                $input=[
                    'uid'=>$uid,
                    'charge'=>$user_id,
                    'time'=>$time,
                    'contract_amount'=>$post['amoneys'],
                    'amount'=>$post['amoneys'],
                    'order_no' => $eid,
                    'order_name'=>$post['cname']
                ];
                $res = $affairModel->apply($input);

                if ($res['status'] == 0){
                    //删除该订单
                    $enginModel->where(['id'=>$insertId])->delete();
                    show(0,'申请失败，请重新提交申请');
                }
                show(1,'申请成功',['url'=>url('Cons/businlist')]);

            }else{
                show(0,'上传失败,请重试!');
            }
		}
		return view('',['uname'=>$uname]);
	}



    /**
     * 消息列表
     * @return [type] [description]
     */
	public function msglist(){
	    if (request()->isAjax()){
            $msgModel = new Message();
            $uid = session('user.id');
            $uid = 20;
            $page = input('?post.page') ? intval(input('post.page')) : 1;
            $pageSize = input('?post.pageSize') ? intval(input('post.pageSize')) : 15;
            $data = $msgModel->appmsgList($uid,'',$page,$pageSize);
            foreach ($data as &$vo){
                $msgLink = $vo['link'];
                if (!empty($msgLink)){
                    $link = json_decode($msgLink,true);
                    if (isset($link['wx'])) $vo['link'] = $link['wx']; else $vo['link'] = '';
                }else{
                    $vo['link'] = '';
                }
            }
            $num = $msgModel->getUnreadMsgNum($uid);
            $res = ['data'=>$data, 'num'=>$num];
            show(1,'',$res);
        }
	    return view();
    }


    /**
     * 微信发货列表
     * @return [type] [description]
     */
    public function getsendlist(){
        if (request()->isAjax()){
            $page = input('post.page') ? input('post.page') : 1;
            $pagesize = input('post.pagesize') ? input('post.pagesize') : 15;
            $pageStart = $page==1 ? 0 : ($page-1)*$pagesize;
            $where = ['type'=>2,'state'=>1];
            $type =  input('?post.type') ? input('post.type') : -1;
            if ($type != -1) $where['logistics'] = $type;
            $rows = Db::table('affair_table')
                ->alias('a')
                ->field('a.id,a.create_t,a.state,a.type,a.order_no,a.order_name,a.logistics,u1.name create_name,u2.name charge_name')
                ->join('user u1','u1.uid=a.create_by','left')
                ->join('user u2','u2.uid=a.charge','left')
                ->where($where)
                ->order('id desc')
                ->limit($pageStart,$pagesize)
                ->select();
            show(1,'',$rows);
        }
    }


    /**
     * 确认收货
     * @return [type] [description]
     */
    public function receipt(){
        if (request()->isAjax()){
            $id = input('id');
            $res = Db::table('affair_table')
                ->where(['id'=>$id])
                ->update(['logistics'=>2]);
            if ($res) show(1,'提交成功');
            show(0,'提交失败');
        }

    }



    /**
     * 标记消息为已读
     * @return [type] [description]
     */
    public function mread(){
        if (request()->isAjax()){
            $id = input('post.id');
            $msgModel = new Message();
            $res = $msgModel->readMsgById($id);
            if ($res) show(1,'修改成功');
            show(0,'修改失败');
        }

    }

    /**
     * 删除消息
     * @return [type] [description]
     */
    public function delmsg(){
        $id = input('get.id');
        $msgModel = new Message();
        $res = $msgModel->delMsgById($id);
        if ($res) show(1,'修改成功');
        show(0,'修改失败');
    }

	/**
	 * 提交产品订单
	 * @return [type] [description]
	 */
	public function aorder(){
		$this->saveWechat();
		if(request()->isAjax()){
			$post = input('post.');
            $oid = date('YmdHis',time()).rand(1000,9999);
            $orderModel = new Order();
            $ugModel = new User_goods();
            $proModel = new Product_info();
            $uid = session('user.id'); //用户id
            $user_id = input('post.uid') ? input('post.uid') : $uid; //负责人的uid
            $time = time();
            $goods_id = input('post.goods_id');
            $goods_num = input('post.goods_num');
            if (!$goods_id || !$goods_num) $this->error('请选择商品或数量');
            $goods_id_arr = explode(',',$goods_id);
            $goods_num_arr = explode(',',$goods_num);
            $num = array_sum($goods_num_arr);
            $data = [
                'oid'=> $oid,
                'uid'=>$uid,
                'aid'=>$post['aid'],
                'notes'=>$post['notes'],
                't1'=>$time,
                'num'=>$num
            ];
            $amount = 0;
            foreach ($goods_id_arr as $k => $v){
                $price = $proModel->getOne(['id'=>$v]);
                $price = $price['price'];
                $amount += $price*intval($goods_num_arr[$k]);
                $add[]=['gid'=>$v, 'num'=>intval($goods_num_arr[$k]), 'price'=>$price];

            }
            $data['acamount'] = $amount;//实际金额
            $data['samount'] = $amount;//应付金额

            $insertId = $orderModel->allowField(true)->insert($data,false,true);

            if($insertId){
                //订单商品记录
                if (!empty($add)){
                    foreach ($add as &$vo) $vo['oid'] = $insertId;
                    $ugModel->saveAll($add);
                }
				$affairModel = new \app\manage\controller\Affairorder();
                $input=[
                    'uid'=>$uid,
                    'charge'=>$user_id,
                    'time'=>$time,
                    'contract_amount'=>$amount,
                    'amount'=>$amount,
                	'order_no' => $oid,
                    'order_name'=>session('user.name')
                ];
				$res=$affairModel->apply($input);

				if ($res['status'] == 0){
                    $orderModel->updInfo(['id'=>$insertId],['is_del'=>1]);
                }

                show(1,'提交成功',['url'=>url('Cons/businlist')]);

            }else{
               show(0,'提交失败');
            }
		}
		$oid = date('YmdHis',time()).rand(1,9999);
		$uname = session('user.name');
		return view('',['oid'=>$oid,'uname'=>$uname]);
	}




    /**
     * 通过订单号查询详情
     * @return [type] [description]
     */
	public function test($order_no='201704241449257927'){
        $order = model('order');
        $data = $order
            ->alias('o')
            ->field('o.id,o.oid,o.uid,o.bid,o.state,o.acamount,o.samount,o.notes,o.t1,a.receiver,a.tel,a.memo,c1.name pname,c2.name cname,c3.name aname')
            ->join([
                ['address a','a.id=o.aid','left'],
                ['china c1','a.pid=c1.id','left'],
                ['china c2','a.cid=c2.id','left'],
                ['china c3','a.aid=c3.id','left'],
            ])
            ->where(['is_del'=>0,'oid'=>$order_no])
            ->find();
        if ($data) $data=$data->toArray();
        if (!empty($data)){
            $ouModel = Db::table('user_goods');
            $res = $ouModel
                ->field('u.num,p.*')
                ->alias('u')
                ->where(['u.oid'=>$data['id']])
                ->join([['product_info p','p.id=u.gid','left']])
                ->select();
            if ($res) $res = endoceArr($res);
            $data['goods'] = $res;
        }

    }

    /**
     * 产品列表
     * @return [type] [description]
     */
	public function prolist(){
        $proModel = new Product_info();
        $data = $proModel->gets();
        show(1,'',$data);
	}


    /**
     * 用户地址列表
     * @return [type] [description]
     */
    public function addresslist(){
        $uid = session('user.id');
        $uid = 20;
        $aModel = new Address();
        $data = $aModel->getAddress(['a.uid'=>$uid], 'a.id,a.uid,a.status,a.receiver,a.tel,c1.name pname,c2.name cname,c3.name aname,a.memo');
        show(1,'',$data);


    }


    /**
     * 新增用户地址
     * @return [type] [description]
     */
    public function insertaddress(){
        $uid = session('user.id');
        $uid = 20;
        $receiver = input('post.receiver',false);
        $tel = input('post.tel',false);
        $pid = input('post.pid',false);
        $cid = input('post.cid',false);
        $aid = input('post.aid',0);
        $memo = input('post.memo',false);
        if ( !$receiver || !$tel || !$pid || !$cid || !$memo ) show(0,'收货地址不够完善，请重新填写');
        $address = [
            'uid'=>$uid,
            'tel'=>$tel,
            'receiver'=>$receiver,
            'pid'=>$pid,
            'cid'=>$cid,
            'aid'=>$aid,
            'memo'=>$memo,
        ];
        $aModel = new Address();
        $res = $aModel->add($address);
        if ($res) show(1,'添加成功',$res);
    }

    /**
     * 更改用户默认地址
     * @return [type] [description]
     */
    public function saveaddressstatus(){
        $aModel = new Address();
        $uid = session('user.id');
        $uid = 20;
        $id = input('post.id',0);
        $save['status'] = 1;
        $aModel->saves(['id'=>$id,'uid'=>$uid],['status'=>1]);
        $aModel->saves(['id'=>['neq',$id], 'uid'=>$uid],['status'=>0]);
        show(1,'更改成功');
    }


    /**
     * 删除收货地址
     * @return [type] [description]
     */
    public function deladdress(){
        $aModel = new Address();
        $uid = session('user.id');
        $uid = 20;
        $id  = input('post.id',0);
        if ($id){
            $res = $aModel->del(['id'=>$id,'uid'=>$uid]);
            if ($res) show(1,'删除成功');
            show(0,'删除失败');
        }
        show(0,'错误操作!');
    }


    /**
     * 搜索获取负责人信息
     * @return [type] [description]
     */
    public function getresponseinfo(){
        $name = input('post.name');
        $user = model('user')
            ->field('uid')
            ->where(['valid'=>1,'name'=>$name])
            ->select();
        $user = endoceArr($user);
        $userModel = model('user');
        $res = [];
        if ($user){
            foreach ($user as $vo){
                $data = $userModel
                    ->alias('u')
                    ->field('u.uid,u.name,group_concat(r2.name SEPARATOR "|") rname')
                    ->join([
                        ['relation r1','u.uid=r1.uid','left'],
                        ['role r2','r2.id=r1.rid','left'],
                    ])
                    ->where(['r2.is_del'=>0,'u.uid'=>$vo['uid']])
                    ->find();
                if ($data){
                    $data = $data->toArray();
                }
                $res[]=$data;
            }
        }
        show(1,'',$res);
    }




    //征询意见
    public function inquiry(){
    	return view();
    }
    
    //抄送界面
    public function copy(){
    	return view();
    }
    
    //重修
    public function rework(){
    	return view();
    }

    //工程征询
    public function enginInquiry(){
    	return view();
    }
    
    //工程抄送界面
    public function enginCopy(){
    	return view();
    }
    
    //工程重修
    public function enginRework(){
    	return view();
    }
    
    //工程返修
    public function enginModify(){
    	return view();
    }
}